#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/11 11:00
# @Author  : CoderCharm
# @File    : role.py
# @Software: PyCharm
# @Desc    :
"""
角色表crud操作
"""
"""
角色表项目 也就是封装
"""
from pydantic import conint
from typing import Optional
from sqlalchemy.orm import Session
from sqlalchemy import func




from api.common.curd_base import CRUDBase
from api.models.auth import AdminRole,Role,Resource
from ..schemas import role_schema


class CRUDRole(CRUDBase[AdminRole, role_schema.RoleCreate, role_schema.RoleUpdate]):

    @staticmethod
    def query_role(db: Session, *, role_id: int) -> Optional[AdminRole]:
        """
        此role_id是否存在
        :param db:
        :param role_id:
        :return:
        """
        return db.query(AdminRole).filter(AdminRole.role_id == role_id).first()

    def create(self, db: Session, *, obj_in: role_schema.RoleCreate) -> Role:
        db_obj = Role(
            name=obj_in.name,
            pid=obj_in.pid,

        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj
    # 创建资源表
    # def create_zi(self, db: Session, *, obj_in: role_schema.RoleCreate) -> Resource:
    #     db_obj = Resource(
    #         # name 菜单名称
    #         name=obj_in.name,
    #         # 排序
    #         pid=obj_in.pid,
    #         # 路径
    #         url=obj_in.url,
    #         restype=obj_in.restype
    #     )
    #     db.add(db_obj)
    #     db.commit()
    #     db.refresh(db_obj)
    #     return db_obj
    # 查询角色的数据
    @staticmethod
    def query_all(db: Session, *, page: int = 1, page_size: conint(le=50) = 10) -> dict:
        """
        查询数据列表
        :param db:
        :param page:
        :param page_size:
        :return:
        """
        temp_page = (page - 1) * page_size
        # 查询数量
        total = db.query(func.count(Role.id)).filter(Role.is_delete == 0).scalar()
        # 查询结果集
        query_obj = db.query(Role).filter(Role.is_delete == 0).offset(
            temp_page).limit(page_size).all()

        items = [{"name": obj.name,
                  "pid": obj.pid} for obj in query_obj]
        return {
            "items": items,
            "total": total
        }
    # 查询分页所有
    # 获取一共有多少条记录
    # 获取当前页面的数据
    # 封装返回


curd_role = CRUDRole(AdminRole)